<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 170px; margin-right: 2px;">
          <el-option label="报修单号" value="repairCode" />
          <el-option label="客户电话" value="contactPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="处理人" value="userName" />
          <el-option label="登记人" value="answer" />
          <el-option label="报修内容" value="repairContent" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="userId">
        <el-select v-model="query.userId" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="登记时间" value="createTime" />
          <el-option label="完成时间" value="signDt" />
          <el-option label="回访时间" value="callTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="状态:" prop="repairStatus">
        <el-select v-model="query.repairStatus" placeholder="请选择">
          <el-option
            v-for="item in repairStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回访结果:" prop="visitStatus">
        <el-select v-model="query.visitStatus" placeholder="请选择">
          <el-option
            v-for="item in visitStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回访调查:" prop="callCheck">
        <el-select v-model="query.callCheck" placeholder="请选择">
          <el-option
            v-for="item in callCheckMap"
            :key="item.backVisitDesc"
            :label="item.backVisitDesc"
            :value="item.backVisitDesc"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="print">打印</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <detail ref="detail" @openPressOrder="openPressOrder" @openTransferOrder="openTransferOrder" @dealConfirm="dealConfirm" @openReturnVisit="openReturnVisit" @openBackOrder="openBackOrder" @openRemark="openRemark" />
    <deal-confirm ref="dealConfirm" />
    <transfer-order ref="transferOrder" />
    <press-order ref="pressOrder" />
    <remark-order ref="remarkOrder" />
    <back-order ref="backOrder" />
    <return-visit ref="returnVisit" :visit-status-map="visitStatusMap" />
  </div>
</template>

<script>
  import {
    queryRepairList,
    queryOwnerList,
    queryRepairOrderMap,
    queryExportRepairOrderList
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import Detail from './components/Detail'
  import DealConfirm from './components/DealConfirm'
  import TransferOrder from './components/TransferOrder'
  import PressOrder from '../../components/PressOrderModal'
  import RemarkOrder from './components/Remark'
  import BackOrder from './components/BackOrder'
  import ReturnVisit from './components/ReturnVisit'
  import moment from 'dayjs'

  const colorObj = {
    1: 'color:#ff0000;',
    2: 'color:#cc33ff;',
    5: 'color:#389E0D;',
    7: 'color:#ff9933;',
    8: 'color:#ff0000;',
    10: 'color:#0066ff;'
  }

  export default {
    name: 'repairOrder',
    components: {
      Detail, DealConfirm, TransferOrder, PressOrder, RemarkOrder, BackOrder, ReturnVisit
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        repairStatusMap: [],
        visitStatusMap: [],
        callCheckMap: [],
        ownersList: [],
        csmType: 'contactPhone',
        csmText: '',
        dateType: 'createTime',
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          userId: '',
          repairStatus: '',
          visitStatus: '',
          callCheck: ''
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData', 'exportDomain'
      ]),
      column: function() {
        return [
          {
            prop: 'repairCode',
            label: '报修单号',
            width: 150,
            render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.repairCode}</el-link>
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 110
          },
          {
            prop: 'userName',
            label: '处理人'
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmOrgName',
            label: '所属机构',
            width: 110
          },
          {
            prop: 'contact',
            label: '联系人'
          },
          {
            prop: 'contactPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'contactAddress',
            label: '联系地址',
            width: 110
          },
          {
            prop: 'rstatus',
            label: '状态',
            width: 110,
            render: (h, { row }) => <span style={colorObj[row.rstatus]}>{ row.rstatus ? formatColumnMap(this.repairStatusMap, 'value', row.rstatus, 'desc') : '未支付' }</span>
          },
          {
            prop: 'answer',
            label: '登记人'
          },
          {
            prop: 'createTime',
            label: '登记时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'createTime',
            label: '预约开始时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'dueTime',
            label: '预约结束时间',
            width: 160,
            render: (h, { row }) => <span>{ row.dueTime && parseTime(row.dueTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'repairContent',
            width: 160,
            label: '客户报修内容'
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'marker1',
            label: '维修员问题反馈',
            width: 110
          },
          {
            prop: 'marker2',
            label: '处理结果',
            width: 110
          },
          {
            prop: 'signDt',
            label: '完成时间',
            width: 110,
            render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'callUserName',
            label: '回访人'
          },
          {
            prop: 'callTime',
            label: '回访时间',
            width: 110,
            render: (h, { row }) => <span>{ row.callTime && parseTime(row.callTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'callResult',
            label: '回访结果',
            width: 110,
            render: (h, { row }) => <span>{ row.callResult ? formatColumnMap(this.visitStatusMap, 'value', row.rstatus, 'desc') : '' }</span>
          },
          {
            prop: 'callCheck',
            label: '回访调查',
            width: 110
          },
          {
            prop: 'marker3',
            label: '回访处理说明',
            width: 110
          },
          {
            prop: 'marker4',
            label: '退单原因',
            width: 110
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.rstatus === 2 && <el-link size='mini' onClick={() => this.openPressOrder(row, $index)}>
                    催单
                  </el-link>}
                  {(row.rstatus === 1 || row.rstatus === 2 || row.rstatus === 6) && <el-link size='mini' onClick={() => this.openTransferOrder(row, $index)}>
                    转派
                  </el-link>}
                  {row.rstatus === 2 && <el-link size='mini' onClick={() => this.dealConfirm(row, $index)}>
                    处理确认
                  </el-link>}
                  {row.rstatus === 10 && <el-link size='mini' onClick={() => this.openReturnVisit(row, $index)}>
                    回访
                  </el-link>}
                  {(row.rstatus === 2 || row.rstatus === 6) && <el-link size='mini' type='danger' onClick={() => this.openBackOrder(row, $index)}>
                    退单/确认
                  </el-link>}
                  <el-link size='mini' onClick={() => this.openRemark(row, $index)}>
                    备注
                  </el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getOwnersList(), this.getMap()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.getOwnersList(value)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query[this.dateType] = moment(this.date[0]).startOf('day').format()
          query[`${this.dateType}End`] = moment(this.date[1]).endOf('day').format()
        }
        query[this.csmType] = this.csmText
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 366) {
          this.$message.warning('日期跨度不能超过一年')
          return
        }
        const res = await queryRepairList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询处理人列表
      async getOwnersList() {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const orgId = this.currentOrg ? this.currentOrg.orgId : -1
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      // 查询所有枚举
      async getMap() {
        const res = await queryRepairOrderMap()
        this.repairStatusMap = JSON.parse(res.data.repairStatus) // 报修单状态
        this.visitStatusMap = JSON.parse(res.data.visitStatusMap) // 回访结果
        this.callCheckMap = JSON.parse(res.data.backVisitInfos) // 回访调查
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      // 点击催单
      async openPressOrder(row) {
        const res = await this.$refs.pressOrder.open(row)
        if (res) {
          if (this.$refs.detail.visible) this.$refs.detail.getDetail(row)
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击处理确认
      async dealConfirm(row) {
        await this.$refs.dealConfirm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击回访
      async openReturnVisit(row) {
        await this.$refs.returnVisit.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击退单
      async openBackOrder(row) {
        await this.$refs.backOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击备注
      async openRemark(row) {
        await this.$refs.remarkOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportRepairOrderList({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      print() {},
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD' || actionColDom[i].tagName === 'TH') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
